package com.seuic.scannerapitest.dao;

import java.io.File;
import java.io.IOException;

import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Environment;
import android.util.Log;

public class scanDao extends SQLiteOpenHelper{

	private static final String DATABASE_NAME = "/mnt/shell/emulated/0/DataBase/Scan.db";
	private static final int DATABASE_VERSION = 1;
	private static final String TABLE_NAME = "barcode_table";

	private static final String ID = "id";

	private static final String BarCode = "BarCode";

	public scanDao(Context context) {
		super(context, DATABASE_NAME, null, DATABASE_VERSION);
		// TODO Auto-generated constructor stub
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		// TODO Auto-generated method stub
		try{
			String sql = "CREATE TABLE " + TABLE_NAME + " (" +  BarCode  + " text);"; //
			db.execSQL(sql);

		}catch(Exception e){
			e.printStackTrace();
		}
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		// TODO Auto-generated method stub
		String sql = "DROP TABLE IF EXISTS " + TABLE_NAME;
		db.execSQL(sql);
		onCreate(db);
	}




	/*删除操作*/
	public boolean delete_barcode(String barcode){
		SQLiteDatabase db = this.getWritableDatabase();

		String sql = "delete from " + TABLE_NAME + " WHERE BarCode = '"+ barcode +   "'";
		try {
			db.execSQL(sql);
			return true;
		} catch (SQLException e){
			Log.e("err", "insert failed");
			return false;
		}finally{
			db.close();
		}
	}




	/*增加操作*/
	public boolean insert_barcode(String barcode){

		try {
			SQLiteDatabase db = this.getWritableDatabase();
			//游标查询每条数据
			String sql = "select * from "+ TABLE_NAME + " where BarCode = ?";

			Cursor cursor = db.rawQuery(sql, new String[]{barcode});
			//定义list存储数据
			if (cursor.getCount() > 0){


			}
			else{
				sql = "insert into "+ TABLE_NAME
						+"(BarCode) values (" + "'"  + barcode + "')";
				try {
					db.execSQL(sql);
					return true;
				}
				catch (SQLException e){
					Log.e("err", "insert failed");
					return false;
				}
				finally{
					db.close();
				}
			}
		}
		catch (Exception e){
			e.printStackTrace();
		}
		return false;
	}


	public String getSDPath(){
		File sdDir = null;
		boolean sdCardExist = Environment.getExternalStorageState()
				.equals(android.os.Environment.MEDIA_MOUNTED);//判断sd卡是否存在
		if(sdCardExist)
		{
			sdDir = Environment.getExternalStorageDirectory();//获取跟目录
		}
		return sdDir.toString();
	}


}
